//
//  ZLOAthorViewModel.swift
//  新浪微博
//
//  Created by 朱玉龙 on 9/27/16.
//  Copyright © 2016 朱玉龙. All rights reserved.
//

import UIKit
class ZLOAthorViewModel: NSObject {

  static let shareOAthor = ZLOAthorViewModel()
    
    let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask,true).last! as NSString).appendingPathComponent("account.plist")
    
    
    var account: ZLAccount? {
        
        didSet {
            
            let string = account?.avatar_large ?? ""
            
            iconURL = NSURL(string: string) as URL?
        }
    }
    
    
    var login: Bool {
        
        if account?.access_token != nil && isExpires == false {
            
            return true
        }
        
        return false
    }
    
    var iconURL: URL?
    
    
   private var isExpires: Bool {
        
        let date = Date()
        
        if  date.compare((account?.expires_date)!) == .orderedAscending {
            
            return false
        }
        return true
    }
    
    
    override init() {
        super.init()
        self.account = loadLocationAccount()
        
        iconURL = URL(string: (self.account?.avatar_large) ?? "")
        
    }
    
    
    
    func loadData(code: String, finished:@escaping (Bool) ->()) {
        
        let dict = ["client_id": client_id,
                    "client_secret": client_secret,
                    "grant_type": "authorization_code",
                    "code": code,
                    "redirect_uri": redirect_uri]
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        ZLNetworkingTools.sharedTools.loadData(method: .POST, urlString:urlString , parameters: dict) { (resonseObject, error) in
            
            if error != nil {
                
                finished(false)
                
                return
            }
      
        let dict = resonseObject as! [String : Any]
            
            self.loadUserInfo(dict: dict, finished: finished)
        }
        
    }
    
    
    private func loadUserInfo(dict: [String : Any], finished: @escaping (Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        //字典中不能添加nil
        let paramters = ["access_token" : access_token,
                         "uid" : uid]
        ZLNetworkingTools.sharedTools.loadData(method: .GET, urlString: urlString, parameters: paramters) { (reponseObject, error) in
            
            if error != nil {
                
                finished(false)
                return
            }
            
            var reponseDict = reponseObject as! [String : Any]
           //这里不明白
            for keyValues in dict {
                
                reponseDict[keyValues.key] = keyValues.value
            }
            
            let account = ZLAccount.init(dict: reponseDict)
            
            self.saveLoacation(account: account)
            
            self.account = account
            
            finished(true)
        }
        
        
        
    }
    
    

    private func saveLoacation(account: ZLAccount) {
        
     NSKeyedArchiver.archiveRootObject(account, toFile: self.path)
      //  /Users/zhuyulong/Library/Developer/CoreSimulator/Devices/C558C45A-295D-4984-A8EA-AD88D1AAA0AF/data/Containers/Data/Application/820A5FA5-171A-4251-9D80-C1EB0EFDC905/Documents/account.plist
        
    }
    
    // /Users/zhuyulong/Library/Developer/CoreSimulator/Devices/C558C45A-295D-4984-A8EA-AD88D1AAA0AF/data/Containers/Data/Application/665C9E68-6CD4-40EB-9E4A-8EC89DA4E7E5/Documents/account.plist
    private func loadLocationAccount() -> ZLAccount? {
        
        let account =  NSKeyedUnarchiver.unarchiveObject(withFile: path) as? ZLAccount
        
        return account
    }
}
